package com.gitee.ywj1352.jdk8;

import org.junit.Test;

import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveTask;

/**
 * @author wenjie.yang on 2019/8/1.
 */
public class ForkAndJoinDemo {


    @Test
    public void fun1(){

        ForkJoinPool pool = new ForkJoinPool();
        ForkJoinCalculate forkJoinCalculate = new ForkJoinCalculate(0, 10000000000L);
        Long invoke = pool.invoke(forkJoinCalculate);
        System.out.println(invoke);
    }



    @Test
    public void test2(){
        long start = System.currentTimeMillis();

        long sum = 0L;

        for (long i = 0L; i <= 10000000000L; i++) {
            sum += i;
        }

        System.out.println(sum);

        long end = System.currentTimeMillis();

        System.out.println("耗费的时间为: " + (end - start)); //34-3174-3132-4227-4223-31583
    }

    private class ForkJoinCalculate extends RecursiveTask<Long>{

        private long start;
        private long end;

        public ForkJoinCalculate(long start,long end){
            this.start = start;
            this.end= end;
        }

        private static final long THRESHOLD = 10000L;



        @Override
        protected Long compute() {
            long length = end - start;
            if (length< THRESHOLD) {
                long sum = 0;
                for (long i = start; i <= end; i++) {
                    sum += i;
                }
                return sum;
            }else{
                long middle = (start +end)/2;
                ForkJoinCalculate left = new ForkJoinCalculate(start,middle);
                left.fork();
                ForkJoinCalculate right = new ForkJoinCalculate(middle,end);
                left.fork();
                return left.join() + right.join();
            }
        }
    }


}
